package com.zh.comm;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "sessionFilter",urlPatterns = {"/*"})
public class UserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
        if(isFilter(uri)){
//            Map user = (Map) session.getAttribute("user");
            if( session == null ||  session.getAttribute("user") == null){
                if(uri.equals("/topay") || uri.equals("/notify_url")|| uri.equals("/return_url")){
                    filterChain.doFilter(request, response);
                    return;
                }
                request.getRequestDispatcher("/user/toLogin").forward(request,response);
            }else{
                filterChain.doFilter(request, response);
            }
        }else{
            filterChain.doFilter(request, response);
        }
    }

    private boolean isFilter(String str){
        boolean flag = false;
        if("/user/toLogin".equals(str) || "/user/login".equals(str)
                || "/user/toRegister".equals(str) || "/user/register".equals(str) ){
            return false;
        }
        int start = str.indexOf(".");
        if(start == -1){
            return true;
        }
        int end = str.indexOf("?");
        if(end == -1){
            end = str.length();
        }
        String url = str.substring(start,end);
        if(".do".equals(url)){
            flag =true;
        }
        return flag;
    }
}
